<template>
  <div class="dialog">
    <el-dialog :title="title" :visible.sync="visible" :close-on-click-modal="false" width="65%">
      <el-form :model="createForm" label-width="120px" label-suffix=":" :rules="rules" ref="createForm">
        <div class="page-panel-title" style="margin-top: 0">用户信息</div>
        <div class="page-panel">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="用户名称" prop="username">
                <el-input v-model.trim="createForm.username" placeholder="请输入用户名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户账号" prop="loginName">
                <el-input v-model.trim="createForm.loginName" placeholder="请输入用户账号" :disabled="isEdit"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="电话号码" prop="phonenum">
                <el-input v-model.trim="createForm.phonenum" placeholder="请输入电话号码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-select v-model="createForm.sex" placeholder="请选择性别" style="width: 100%">
                  <el-option label="男" value="0" />
                  <el-option label="女" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item prop="birthday" label="出生日期">
                <el-date-picker v-model.trim="createForm.birthday" type="date" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" placeholder="请选择出生日期" style="width: 100%"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="identityCardNo">
                <el-input v-model.trim="createForm.identityCardNo" placeholder="请输入身份证号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="所属区域" prop="regionCodePath">
                <el-cascader :key="resetCascader" ref="regionCascader" v-model="createForm.regionCodePath" :props="props"
                  style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="家庭住址" prop="address">
                <el-input v-model.trim="createForm.address" placeholder="请输入家庭住址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="学历" prop="degree">
                <el-select v-model="createForm.degree" placeholder="请选择学历" style="width: 100%">
                  <el-option v-for="it in degreeList" :key="it.dictItemCode" :label="it.dictItemName"
                    :value="it.dictItemCode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行卡号" prop="bankAccount">
                <el-input v-model.trim="createForm.bankAccount" placeholder="请输入银行卡号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开户网点" prop="bankBranch">
                <el-input v-model.trim="createForm.bankBranch" placeholder="请输入开户网点"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行名称" prop="bankName">
                <el-input v-model.trim="createForm.bankName" placeholder="请输入银行名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input v-model.trim="createForm.emergencyContact" placeholder="请输入紧急联系人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系人电话" prop="emergencyPhonenum">
                <el-input v-model.trim="createForm.emergencyPhonenum" placeholder="请输入紧急联系人电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="page-panel-title">技能信息</div>
        <div class="page-pane2">
          <el-button size="mini" type="info" @click="addLevel()">新增技能</el-button>
        </div>
        <div class="page-panel">
          <el-row v-for="(item, index) in skillList" :key="index" :gutter="24">
            <el-col :span="11">
              <el-form-item label="技能名称">
                <el-select v-model="item.skillTypeId" placeholder="请选择技能名称"
                  @change="onSelectSkill(item.skillTypeId, index)" style="width: 100%">
                  <el-option v-for="it in skillData" :key="it.id" :label="it.skillTypeName" :value="it.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="技能等级">
                <el-select v-model="item.skillLevelId" placeholder="请选择技能等级" style="width: 100%">
                  <el-option v-for="it in item.skillLevelList" :key="it.id" :label="it.skillLevel" :value="it.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" v-if="index != 0">
              <el-button size="small" type="danger" @click="deleteLevel(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeNetWorker()">关 闭</el-button>
        <el-button type="primary" @click="confirmData('createForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  sysMechanicInfoSave,
  sysMechanicInfoUpdate,
  sysMechanicInfoFindById,
  checkLoginNameIsExists,
  findListForSelect,
  findSkillLevelList,
  sysRegionListByParentCode
} from "@/api/index";
import { getDictionaryItemMap } from "@/api/common";
import { validatePhone } from '@/utils/validate'
export default {
  name: "UserDialog",
  props: {
    exterOrg: {
      type: Object,
      default: {}
    },
  },
  data () {
    return {
      title: "",
      isEdit: false,
      visible: false,
      createForm: {
        empSource: 'outside',
        empType: "1"
      },
      skillList: [],
      skillData: [],
      degreeList: [],
      defaultProps: {
        children: 'children',
        label: 'resourceName'
      },
      resetCascader: 0,
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          setTimeout(async () => {
            const res = await this.getTreeByParentCode(node)
            return resolve(res)
          })
        }
      },
      rules: {
        username: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
        loginName: [
          { required: true, message: "请输入用户账号", trigger: "blur" },
          { validator: this.validateLoginName },
        ],
        phonenum: [{ required: true, message: "请输入电话号码", trigger: "blur" }, { validator: validatePhone, trigger: 'blur' }],
        regionCodePath: [{ required: true, message: "请选择所属区域", trigger: "blur" }],
      },
    };
  },
  created () { },
  mounted () { },
  methods: {
    add () {
      this.title = "新增";
      this.isEdit = false;
      this.createForm = {
        empSource: 'outside',
        empType: "1"
      };
      this.skillList = [];
      this.addLevel();
      this.init();
      this.visible = true;
    },
    edit (val) {
      this.title = "编辑";
      this.isEdit = true;
      this.visible = true;
      this.skillList = [];
      this.init();
      this.resetCascader++;
      sysMechanicInfoFindById({ id: val.id }).then((res) => {
        if (res.data.code == 0) {
          this.createForm = res.data.data;
          this.createForm.empSource = 'outside'
          let skillList = res.data.data.skillList;
          if (skillList.length > 0) {
            for (var i = 0; i < skillList.length; i++) {
              this.initSkillLevel(skillList[i], i);
            }
          }
        }
      });
    },
    initSkillLevel (item, index) {
      setTimeout(async () => {
        const res = await this.getSkillLevelBySkillTypeId(item.skillTypeId);
        item.skillLevelList = res;
        this.skillList.push(item);
      });
    },
    init () {
      let data = {
        storeId: this.exterOrg.id
      }
      findListForSelect(data).then((res) => {
        if (res.data.code == 0) {
          this.skillData = res.data.data;
          this.skillData.forEach((element) => {
            element.skillTypeName =
              element.skillTypeName +
              (element.skillPriceType == "0" ? "（时薪）" : "（件薪）");
          });
        }
      });
      getDictionaryItemMap({ codeArr: "degree" }).then((res) => {
        let data = res.data;
        if (data && data.code == 0) {
          this.degreeList = data.data.degree;
        }
      });
    },
    getTreeByParentCode (node) {
      return new Promise((resolve, reject) => {
        let params = {}
        if (node.data) {
          params = { parentCode: node.data.value }
        }
        sysRegionListByParentCode(params).then(res => {
          if (res.data.code == 0) {
            const nodes = Array.from(res.data.data).map(item => ({
              value: item.code,
              label: item.name,
              leaf: item.type == "area"
            }))
            resolve(nodes)
          }
        })
      })
    },
    getSkillLevelBySkillTypeId (skillTypeId) {
      return new Promise((resolve, reject) => {
        let params = {
          skillTypeId: skillTypeId,
        };
        findSkillLevelList(params).then((res) => {
          if (res.data.code == 0) {
            resolve(res.data.data);
          }
        });
      });
    },
    onSelectSkill (skillTypeId, index) {
      setTimeout(async () => {
        const res = await this.getSkillLevelBySkillTypeId(skillTypeId);
        this.skillList[index].skillLevelList = res;
        this.skillList[index].skillLevelId = "";
      });
    },
    // 增加行
    addLevel () {
      this.skillList.push({
        skillTypeId: "",
        skillLevelId: "",
        skillLevelList: [],
      });
    },
    // 删除行
    deleteLevel (index) {
      this.skillList.splice(index, 1);
    },
    confirmData (formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          let flag = true;
          this.skillList.forEach(item => {
            if (!item.skillTypeId || !item.skillLevelId) {
              flag = false;
              return;
            }
          })
          if (!flag) {
            this.$message.info("请检查技能信息是否全部选择！")
          } else {
            this.createForm.skillList = this.skillList;
            // this.createForm.regionCode = this.createForm.regionCodePath[this.createForm.regionCodePath.length - 1]
            if (this.createForm.id) {
              sysMechanicInfoUpdate(this.createForm).then((res) => {
                const data = res.data;
                if (data.code == 0) {
                  this.$message.success("修改成功");
                  this.$emit("ok");
                  this.closeNetWorker();
                } else {
                  this.$message.error(data.data || "修改失败");
                }
              });
            } else {
              this.createForm.orgId = this.exterOrg.id
              sysMechanicInfoSave(this.createForm).then((res) => {
                const data = res.data;
                if (data.code == 0) {
                  this.$message.success("新增成功");
                  this.$emit("ok");
                  this.closeNetWorker();
                } else {
                  this.$message.error(data.data || "新增失败");
                }
              });
            }
          }
        }
      });
    },
    closeNetWorker () {
      this.createForm = {
        empSource: 'outside'
      };
      this.skillList = [];
      this.visible = false;
    },
    validateLoginName (rule, value, callback) {
      if (this.isEdit) {
        callback();
        return;
      }
      let params = {
        loginName: value,
      };
      checkLoginNameIsExists(params).then((res) => {
        if (res && res.data.code == 0) {
          if (!res.data.data) {
            callback();
          } else {
            callback("用户账号已经存在");
          }
        } else {
          callback(res.data.data);
        }
      });
    },
  },
};
</script>
<style scoped lang="less"></style>
